//
//  WYJOAuthViewController.swift
//  MySinaWeibo
//
//  Created by eastriver on 16/10/7.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit
import SVProgressHUD
class WYJOAuthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    // MARK: 将根视图改为webView
    override func loadView() {
        
        view = webView
        webView.delegate = self
        view.isOpaque = false
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        setupNavBar()
        loadOAuthPage()
    }
    
    // MARK: 设置导航条
    private func setupNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        // 设置自动填充
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(fillAccount))
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = '13061818102',document.getElementById('passwd').value = 'believe070057'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
        
    }
    
    deinit {
        print("OAuth控制器被销毁了")
    }
    
    
}
// 分类
extension WYJOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString
        let flag = "code="
        if (urlString?.contains(flag))! {
            // 授权成功
            let query = request.url?.query ?? ""
            //            print(query)
            //            print("~~~~~~~~~~~~~~~~~~~~~~")
            let code = (query as NSString).substring(from: flag.characters.count)
            //            print(code)
            //            print("~~~~~~~~~~~~~~~~~~~~~~")
            // 获取授权
            WYJUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code: code, finished: { (success) in
                if success != true {
                    SVProgressHUD.show(withStatus: "网络错误")
                    return
                }
                print("登录获取用户信息成功")
             // 切换应用程序的根控制器
                self.dismiss(animated: true, completion: { 
                    // 发出通知
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationName), object: nil)
                })
            })

            return false
        }
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        // 显示等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 关闭等待指示器
        SVProgressHUD.dismiss()
    }
    /*
    internal func loadAccessToken(code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        WYJNetworkTool.sharedTool.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                return
            }
            //            print(responseObject)
            // 获取用户信息
            self.loadUserInfo(dict: responseObject as! [String : Any])
            
        }
    }
    private func loadUserInfo(dict: [String: Any]) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token": access_token, "uid": uid]
        WYJNetworkTool.sharedTool.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                return
            }
//            print(responseObject)
            // 字典转模型，将用户信息保存到要地
            var userInfoDict = responseObject as! [String: Any]
            // 合并字典
            for keyValues in dict {
                userInfoDict[keyValues.key] = keyValues.value
            }
            let userAccout = WYJUserAccount(dict: userInfoDict)
//            print(userAccout)
            // 把用户信息保存到本地
            self.saveUserAccount(userAccount: userAccout)
        }
    }
    private func saveUserAccount(userAccount: WYJUserAccount) {
        // 获取沙盒中Documents文件夹路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
        // 拼接文件存放路径
        let filePath = (path! as NSString).appendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
        print(filePath)
        
    }
    */
   
}
